package com.CST.util;

import io.jsonwebtoken.*;
import java.util.*;
import org.slf4j.*;
import org.springframework.stereotype.*;

/**
 * JwtToken生成的工具类 Created by macro on 2018/4/26.
 */
@Component
public class JwtTokenUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String TOKEN = "token";
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    public static String secret = "CST_token";
    //private static String secret = "iwqjhda8232bjCST432[cicada-smile]";
    public static Long expiration = 604800L;

    /**
     * 根据负责生成JWT的token
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()).signWith(
                SignatureAlgorithm.HS512, secret).compact();
    }


    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "admin");
        map.put("userPassword","123456");


        System.out.println("************************************");

        System.out.println(generateToken(map));

    }



    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
	  Claims claims = null;
	  try {
		claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
	  } catch (Exception e) {
		LOGGER.info("JWT格式验证失败:{}", token);
	  }
	  return claims;
    }

    /**
     * 生成token的过期时间
     */
    private static Date generateExpirationDate() {
	  return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
	  String username;
	  try {
		Claims claims = getClaimsFromToken(token);
		username = claims.getSubject();
	  } catch (Exception e) {
		username = null;
	  }
	  return username;
    }


    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
	  Date expiredDate = getExpiredDateFromToken(token);
	  return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
	  Claims claims = getClaimsFromToken(token);
	  return claims.getExpiration();
    }


    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
	  return !isTokenExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
	  Claims claims = getClaimsFromToken(token);
	  claims.put(CLAIM_KEY_CREATED, new Date());
	  return generateToken(claims);
    }
}
